<template>
    <div class="container">
        <div class="header-actions">
            <el-button type="primary" class="createBtn" @click="createRow">新增</el-button>

            <div class="search-form">
                <el-input v-model="searchTitle" placeholder="请输入标题搜索" clearable>
                    <template #append>
                        <el-button @click="searchData">搜索</el-button>
                    </template>
                </el-input>
            </div>
        </div>

        <el-table :data="tableData.data" style="width: 100%;margin-top: 20px;">
            <el-table-column v-for="(model, index) in tableDataDetail" :prop="model.field" :label="model.name"
                :key="index">
                <template #default="scope">
                    <div v-if="model.field === 'imageUrl'">
                        <el-image :src="scope.row[model.field]" alt="Image"
                            style="width: 60px; height: 60px; object-fit: cover;"
                            :preview-src-list="[scope.row[model.field]]"
                            fit="cover">
                            <template #error>
                                <div class="image-error">
                                    <el-icon><picture-filled /></el-icon>
                                    <div class="error-text">加载失败</div>
                                </div>
                            </template>
                        </el-image>
                    </div>
                    <div v-else-if="model.field === 'isPinned'">
                        <el-tag :type="scope.row[model.field] ? 'success' : 'info'">
                            {{ scope.row[model.field] ? '已置顶' : '未置顶' }}
                        </el-tag>
                    </div>
                    <div v-else>
                        {{ scope.row[model.field] }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="replyRow(scope.$index)">回复</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
            :current-page="currentPage" @current-change="handlePageChange" @size-change="handlePageSizeChange"
            style="margin-top: 20px;" />


    </div>
    
    <!-- 回复对话框 -->
    <div v-if="isReply" class="modal-form">
        <div class="modal-content">
            <h3 class="modal-title">回复反馈</h3>
            <div class="form-items">
                <div class="form-item">
                    <label>回复内容</label>
                    <el-input v-model="replyForm.answeredBy" type="textarea" rows="4" placeholder="请输入回复内容"></el-input>
                </div>
            </div>
            <div class="modal-footer">
                <el-button @click="isReply = false">取消</el-button>
                <el-button type="primary" @click="submitReply">提交回复</el-button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
    import { reactive, ref, onMounted } from 'vue';
    import axios from 'axios';
    import { ElMessage } from 'element-plus'
    import { PictureFilled, Close, Plus, UploadFilled } from '@element-plus/icons-vue'

    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const searchTitle = ref('')

    const tableDataDetail = reactive([
        { field: 'id', name: '编号' },
        { field: 'answer', name: '回答内容' },
        { field: 'answeredBy', name: '回复' },
        { field: 'userId', name: '用户ID' },
        { field: 'createdAt', name: '创建时间' },
        { field: 'updatedAt', name: '更新时间' }
    ])

    const tableData = reactive({ data: [] })

    const handlePageChange = (page: number) => {
        currentPage.value = page
        fetchTableData()
    }

    const handlePageSizeChange = (size: number) => {
        pageSize.value = size
        fetchTableData()
    }

    function fetchTableData() {
        axios.get('http://localhost:9090/questionAnswer/getAll').then((res) => {
            tableData.data = res.data
            total.value = res.data.length
        }).catch(error => {
            ElMessage.error('加载数据失败')
        })
    }

    function searchData() {
        if (!searchTitle.value) {
            fetchTableData()
            return
        }
        
        axios.post('http://localhost:9090/api/questionAnswer/search', {
            title: searchTitle.value
        }).then((res) => {
            if (res.data) {
                tableData.data = res.data
                total.value = res.data.length
            } else {
                tableData.data = []
                total.value = 0
                ElMessage.warning('未找到相关数据')
            }
        }).catch(() => {
            ElMessage.error('搜索失败')
        })
    }

    function deleteRow(index: number) {
        const id = tableData.data[index].id
        axios.delete(`http://localhost:9090/api/questionAnswer/${id}`).then(() => {
            fetchTableData()
            ElMessage.success('删除成功')
        }).catch(() => {
            ElMessage.error('删除失败')
        })
    }

    const CreateDataDetail = reactive({
        data: [
            { value: '', field: 'answer', name: '回答内容' },
            { value: '', field: 'answeredBy', name: '回答者' },
            { value: '', field: 'userId', name: '用户ID' }
        ]
    })

    const isCreate = ref(false)

    function createRow() {
        console.log('createRow')
        axios.get('http://localhost:9090/questionAnswer/getAll').then((res) => {
            tableData.data = res.data
            total.value = res.data.length
        }).catch(error => {
            ElMessage.error('加载数据失败')
        })
    }

    function realyCreate() {
        const data = {
            answer: CreateDataDetail.data.find(item => item.field === 'answer')?.value,
            answeredBy: CreateDataDetail.data.find(item => item.field === 'answeredBy')?.value,
            userId: Number(CreateDataDetail.data.find(item => item.field === 'userId')?.value)
        }

        if (!data.answer || !data.answeredBy || !data.userId) {
            ElMessage.warning('请填写完整信息')
            return
        }

        axios.post('http://localhost:9090/api/questionAnswer', data).then(() => {
            fetchTableData()
            isCreate.value = false
            ElMessage.success('新增成功')
        }).catch(() => {
            ElMessage.error('新增失败')
        })
    }

    const isWrite = ref(false)
    const ruleForm = reactive({
        id: null,
        data: [
            { value: '', field: 'id', name: '编号' },
            { value: '', field: 'answer', name: '回答内容' },
            { value: '', field: 'answeredBy', name: '回答者' },
            { value: '', field: 'userId', name: '用户ID' }
        ]
    })
    
    // 回复对话框相关状态
    const isReply = ref(false)
    const replyForm = reactive({
        id: null,
        answer: '',
        answeredBy: ''
    })

    function writeRow(index: number | null) {
        if (index !== null) {
            const item = tableData.data[index]
            ruleForm.id = item.id
            ruleForm.data.forEach(field => {
                if (field.field === 'image') {
                    field.value = item['imageUrl'] // 修正字段名
                } else {
                    field.value = item[field.field]
                }
            })
            isWrite.value = true
        } else {
            isWrite.value = false
        }
    }
    
    // 实现回复功能
    function replyRow(index: number) {
        const item = tableData.data[index]
        replyForm.id = item.id
        replyForm.answer = ''
        replyForm.answeredBy = ''
        isReply.value = true
    }
    
    // 提交回复
    function submitReply() {
        if ( !replyForm.answeredBy) {
            ElMessage.warning('请填写完整回复信息')
            return
        }
        
        const data = {
            id: replyForm.id,
            answeredBy: replyForm.answeredBy
        }
        
        axios.put(`http://localhost:9090/questionAnswer/update`, data).then(() => {
            fetchTableData()
            isReply.value = false
            ElMessage.success('回复成功')
        }).catch(() => {
            ElMessage.error('回复失败')
        })
    }

    function realyWrite() {
        const data = {
            id: ruleForm.id,
            answer: ruleForm.data.find(item => item.field === 'answer')?.value,
            answeredBy: ruleForm.data.find(item => item.field === 'answeredBy')?.value,
            userId: Number(ruleForm.data.find(item => item.field === 'userId')?.value)
        }

        axios.put(`http://localhost:9090/api/questionAnswer`, data).then(() => {
            fetchTableData()
            isWrite.value = false
            ElMessage.success('修改成功')
        }).catch(() => {
            ElMessage.error('修改失败')
        })
    }
    
    // 页面加载时自动获取数据
    onMounted(() => {
        fetchTableData()
    })
</script>


<style scoped>
    .container {
        padding: 20px;
    }

    .header-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .search-form {
        width: 300px;
    }

    .modal-form {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 999;
    }

    .modal-content {
        background: white;
        padding: 30px;
        border-radius: 8px;
        width: 500px;
        overflow: visible;
    }

    .modal-title {
        text-align: center;
        margin-bottom: 20px;
        font-size: 18px;
        color: #333;
    }

    .form-items {
        margin-bottom: 20px;
    }

    .form-item {
        margin-bottom: 15px;
    }

    .form-item label {
        display: block;
        margin-bottom: 8px;
        color: #606266;
    }

    .modal-footer {
        display: flex;
        justify-content: center;
        gap: 20px;
        margin-top: 30px;
    }

    .el-pagination {
        display: flex;
        justify-content: center;
    }

    .el-pagination .el-pager li.is-active {
        background-color: #409EFF;
        color: white;
    }
</style>
